package org.apache.shardingsphere.elasticjob.lite.ui.security;

import com.google.gson.Gson;
import org.apache.shardingsphere.elasticjob.lite.ui.web.response.ResponseResultUtil;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Session filter.
 */
public class SessionFilter implements Filter {

    private static final String SESSION_LOGIN_USER = "session_login_user";
    private final Gson gson = new Gson();

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;
        if (httpRequest.getSession().getAttribute(SESSION_LOGIN_USER) != null) {
            filterChain.doFilter(httpRequest, httpResponse);
        } else {
            respondWithOverdue(httpResponse);
        }
    }

    @Override
    public void destroy() {
    }

    private void respondWithOverdue(final HttpServletResponse httpResponse) throws IOException {
        httpResponse.setContentType("application/json");
        httpResponse.setCharacterEncoding("UTF-8");
        httpResponse.getWriter().write(gson.toJson(ResponseResultUtil.handleUnauthorizedException("Session Overdue.")));
    }
}
